import { Checkbox, Col, Form, Input, message, Modal, Row } from 'antd'
import React, { useEffect, useState } from 'react'
import userApi from '@/api/project'
import { CheckboxValueType } from 'antd/lib/checkbox/Group'
export default function rightModal(props: any) {
  const CheckboxGroup = Checkbox.Group
  const { getUserList, isRoleSelect, modal, showModal } = props
  // 半选
  const [indeterminate, setIndeterminate] = useState(true)
  const [checkAll, setCheckAll] = useState(false)
  //  已有的角色
  const [selectRole, setSelectRole] = useState<string[]>([])
  //   全部角色
  const [allRole, setAllRole] = useState<{ value: string; label: string }[]>([])
  const onSave = async () => {
    try {
      await userApi.saveUser(isRoleSelect.id, selectRole)
      message.success('保存成功')
      getUserList()
    } catch (error) {
      message.error(error)
    } finally {
      showModal(false)
    }
  }
  //  已有的角色

  const onChange = (list: CheckboxValueType[]) => {
    setIndeterminate(!!list.length && list.length < allRole.length)
    setCheckAll(list.length === allRole.length)
  }
  const onCheckAllChange = (e: any) => {
    setIndeterminate(false)
    setCheckAll(e.target.checked)
  }
  // 添加选中状态
  const selectCheck = (checked: boolean, id: string) => {
    if (checked) {
      setSelectRole([...selectRole, id])
    } else {
      setSelectRole(selectRole.filter((item) => item != id))
    }
  }
  const reqUserRole = async () => {
    try {
      let result = await userApi.reqUserRight(isRoleSelect.id)
      setAllRole(result.allRolesList.map((item) => ({ value: item.id, label: item.roleName })))
      setSelectRole(result.assignRoles.map((item) => item.id))
    } catch (error) {}
  }

  useEffect(() => {
    if (!isRoleSelect?.id && !modal) return
    reqUserRole()
  }, [isRoleSelect, modal])
  return (
    <>
      <Modal
        forceRender={true}
        title="设置角色"
        open={modal}
        onOk={onSave}
        onCancel={() => {
          showModal(false)
        }}
      >
        <Form>
          <Form.Item label="用户名">
            <Input value={isRoleSelect?.username} disabled />
          </Form.Item>
          <Form.Item label="角色列表">
            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
              全选
            </Checkbox>
            <br></br>
            <CheckboxGroup value={selectRole} onChange={onChange}>
              <Row>
                {allRole.map((item) => {
                  return (
                    <Col key={item.value}>
                      <Checkbox value={item.value} onChange={(e) => selectCheck(e.target.checked, item.value)}>
                        {item.label}
                      </Checkbox>
                    </Col>
                  )
                })}
              </Row>
            </CheckboxGroup>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
